/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package commons;


import java.io.BufferedOutputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.io.*;
import java.text.SimpleDateFormat;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;







import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

/**
 *
 * @author TonyLogic
 */
public class DataProcessing{
    
    public static String To3DigitString(String aNumber)
    {
        int x =  Integer.parseInt(aNumber);
        String back = "";
        if(x<10)
            {
              	 back = "00"+x;       	      	 
            }else if (x>=10 && x< 100)
            {
        	back ="0"+x;   		
            }
            else if (x >= 100)
            {
                 back = aNumber;
           
            }        	
        
        return back;
    }
	
		
    public static void makeDirAndMoveFile(File searchDir)
    {
        
        String writeDir = "F:/Switchbox/Equivital_core_patches/";
        
        List<File> Files = new ArrayList<File>();
        
        for(int z=002; z<145; z++)
        {      	
            if(z<10)
            {
              	 File dir =new File(writeDir+"00"+z);       	 
        	 System.out.println(dir.mkdir());

            }else if (z>=10 && z< 100)
            {
        	File dir =new File(writeDir+"0"+z);
       		System.out.println( dir.mkdir());
            }
            else if (z >= 100)
            {
            (   new File(writeDir+z)).mkdir();
            System.out.println( writeDir+z);
            }        	
        }
            
        // Move Files equivital files
        for( int z=002; z<145; z++ )
       {
  	
            String PatientNumber = "0";   	
            if(z<10)
            {
        
                PatientNumber="00"+z;
           }else if (z>=10 && z< 100)
            {
                PatientNumber="0"+z;
            }
            else if (z >= 100)
            {
                PatientNumber=Integer.toString(z);
            }
        	
          System.out.println(PatientNumber);        
          IOhandler.searchForDatFiles(searchDir,Files,PatientNumber,false,false);
        	
     
        
       for (int i=0;i<Files.size();i++)
        {
          
    	   String pathPatientNumber = Character.toString( Files.get(i).getPath().charAt(28))+
    			   Character.toString( Files.get(i).getPath().charAt(29))+
    			   Character.toString( Files.get(i).getPath().charAt(30));	        	
       	if(Files.get(i).getPath().contains("Core_Patch") && pathPatientNumber.contentEquals(PatientNumber) )
       	{
       		   File CorePatch  = Files.get(i); 
       	           String path = CorePatch.getPath();
        		      		
                System.out.println(path);
        	System.out.println(path.substring(path.length()-23, path.length()));
        		
  		String dir = "F:/Switchbox/Equivital_core_patches/"+PatientNumber+"/"+path.substring(path.length()-23, path.length());
  		DataProcessing.moveFile(path, dir);
   		
       	}
          if( Files.get(i).getPath().contains("Accelerometer") && Files.get(i).getName().endsWith(".csv"))
           {                
                 DataProcessing.AggraTimeSeries(Files.get(i), 300);
               return;
            }
       }
        
       Files.clear();
       
      }
        
        
    }
	
    
    public static void moveFile(String aFile, String dir)
   { 
		
		
		BufferedReader br = null;
		BufferedOutputStream io= null;
		
		String output =" ";
        try{
    		           
        br = new BufferedReader(new FileReader(aFile));
    	io = new BufferedOutputStream(new FileOutputStream(dir));
 		
         for(String readLine; (readLine = br.readLine()) !=null;)
         {
			 	
        	  readLine = readLine+"\n"; 
                  byte bites[] = readLine.getBytes();
                  io.write(bites);		 
         }
		
		br.close();
                io.close();
		
		}  catch (Exception e){
         
            System.out.println(e.getMessage());
         }
	
  }
    
    
    public static boolean checkTimeDiff(Date aStartDate, Date aEndDate, int TimeLimit)
  {
	  
	  long difference = aEndDate.getTime() - aStartDate.getTime();
	  
	  if(difference/1000 >=TimeLimit){
		  return true;
	  }
	  else{
		  return false;
	  }
	  
  }
    
    
    public static void AggraTimeSeries(File aFile, int TimeLimit)
    {
       System.out.println("Deze heb ik gekregen"+aFile.getPath());
       ArrayList AggraValues = new ArrayList<String[]>();
       BufferedOutputStream io = null;
       BufferedReader br = null;
       
       DecimalFormat df = new DecimalFormat("0.00");
       DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
       Date dateBegin = null;
                   
       boolean foundData = false;
       
       try{
           
         br = new BufferedReader(new FileReader(aFile.getPath()));                 
         io = new BufferedOutputStream(new FileOutputStream(aFile.getPath()+"_comp.csv"));
         
         
                              
         for(String readLine; (readLine = br.readLine()) !=null;)
         {
           
            
          if ( foundData == true )   
          {
                                            
            if(AggraValues.isEmpty() == false )
            {
            	AggraValues.add(readLine.split(",")); 
            	
                String splitedValues[] = readLine.split(",");                                                                                            
                Date dateEnd = formatter.parse(splitedValues[0]);
                           
                                       
                if(checkTimeDiff(dateBegin,dateEnd,TimeLimit) ){
                                     
                    String[] firstValue = (String[]) AggraValues.get(0);
                                   
                    for(int z=1; z<AggraValues.size(); z++)
                    {
                        String[] currentValue =  (String[]) AggraValues.get(z);
                      
                       for(int y=1; y<firstValue.length;y++) 
                       {                            
                           double aggraVal = Double.parseDouble(firstValue[y])+Double.parseDouble(currentValue[y]);
                           firstValue[y] = Double.toString(aggraVal) ;                         
                       }
                      
                    }
                     
                                     
                    String writeToFile = splitedValues[0]+",";
                    int divide =AggraValues.size();
                    System.out.println(divide);
                    
                    for(int y=1; y<firstValue.length;y++) 
                       {
                           double AggraValue =Double.parseDouble(df.format( Double.parseDouble( firstValue[y])/divide).replace(",", "."));                            
                           writeToFile=writeToFile+AggraValue+",";                          
                       }
                    writeToFile = writeToFile+"\n";
                    
                    //System.out.println("Dit gaat hij schrijven= \n"+writeToFile);
                    byte bites[] = writeToFile.getBytes();                 
                    io.write(bites);
                    AggraValues.clear();
     
                }
                else{
                    
                    AggraValues.add(readLine.split(","));  
                }
            }
            else{ 
                String inputValues[] = readLine.split(",");
                dateBegin = formatter.parse(inputValues[0]);
                AggraValues.add(inputValues);   
            }
          }
           else  if(foundData == false)
             {
                 foundData = readLine.matches("[0-9[,][-][:][.] ]+") ;
             }
         
       
               
         }
         
           io.close();
           br.close();
           
              
        }
        catch (Exception e){
            System.out.append("wtf");
            System.out.println(e.getMessage());
         }
      
       
        
              
    }
    
    
    public static String to24Hours(String aHour, int pos)
    {
	   String retString = aHour;
	   
	   if(aHour.equals("0:00"))
	   {
		   retString ="24:00";
	   }
	   
	   if(aHour.equals("ng") || aHour.equals("") ){
		   
		   if(pos==1 ){
		   retString = "8:00";
		   }
		   
		   
		   if(pos==2 ){
		   retString = "9:00";
		   }
		   
		   
		   if(pos==3 ){
		   retString = "22:00";
		   }
		   
		   
		   if(pos==4 ){
		   retString = "23:00";
		   }
		   
		   
	   }
	   
	   return retString;
   }

   public static void CleanEquivital( List<File> aPatientEqvuivitalFiles, File equivitalPath, File aPillTimeSchema,int TimeLimit, String aPatientNumber )
   {
	   	  
	   ArrayList<String[]> AggraValues = new ArrayList(); 
	   
       DecimalFormat df = new DecimalFormat("0.00");
       DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
       DateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy hh:mm");
       DateFormat formatter2 = new SimpleDateFormat("MM/dd/yyyy");
	   Calendar c = GregorianCalendar.getInstance();
	   Calendar c1 = GregorianCalendar.getInstance();
       Date dateBegin = null;
       Date dateEnd = null;
   	    			 	   
     
       String patientNumbers = "";
       String[] pillInfo = new String[4];
       Date[] datePills = new Date[3];
       ArrayList<Date> dateCharge = new ArrayList<Date>();
       
       BufferedOutputStream io = null;
       BufferedOutputStream finalio = null; 
       BufferedReader br = null;
       
           
       try
       { 
    	       	   
    	   // First find the pill assiocaited to the patient
    	    Workbook w = Workbook.getWorkbook(aPillTimeSchema);     
         	Sheet sheet = w.getSheet(0);
         	
         	
         	        	      	        
         	for(int i = 3; i<sheet.getRows();i++){
         	
         		Cell cell = sheet.getCell(0, i);
         		        	
         		if(Integer.parseInt(aPatientNumber) == Integer.parseInt(cell.getContents()) )
         		{
         			// Get the pill information.
         			pillInfo[0] = sheet.getCell(1, i).getContents();        			        		
         			pillInfo[1] = sheet.getCell(2, i).getContents();        			
         			pillInfo[2] = sheet.getCell(3, i).getContents();        			
         			pillInfo[3] = sheet.getCell(7, i).getContents(); 
         			   			
         			// Get the charging time.
         			String beginPieceDate[] = sheet.getCell(8,i).getContents().split("/");
         			String perfectBeginDate = beginPieceDate[0]+"/"+beginPieceDate[1]+"/"+"20"+beginPieceDate[2];
         			
         			c1.setTime(formatter2.parse(perfectBeginDate));
         			
         			
         			String chargeTime1Begin = perfectBeginDate+" "+to24Hours(sheet.getCell(9,i).getContents(),1);
         			String chargeTime1End = perfectBeginDate+" "+to24Hours(sheet.getCell(10,i).getContents(),2);
         			
         			
         			dateCharge.add(formatter1.parse(chargeTime1Begin));
         			dateCharge.add(formatter1.parse(chargeTime1End));
         			c1.add(Calendar.DATE, 1);
         			
         			for(int xi= 11; xi<23; xi= xi+6){
         				String InDate = formatter2.format(c1.getTime());
         				
         				String chargeTimeMorBegin = InDate+" "+to24Hours(sheet.getCell(xi,i).getContents(),1);
         				String chargeTimeMorEnd = InDate+" "+ to24Hours(sheet.getCell(xi+1,i).getContents(),2);
         				
         				String chargetTimeEveBegin = InDate+" "+to24Hours(sheet.getCell(xi+2,i).getContents(),3);
         				String chargeTimeEveEnd = InDate+" "+to24Hours(sheet.getCell(xi+3,i).getContents(),4);
         				
         				String Extra = sheet.getCell(xi+4,i).getContents();
         				String ExtraChargeBegin = "";
         				String ExtraChargeEnd = "";
         				
         				if(!Extra.isEmpty()){
         					ExtraChargeBegin = InDate+" "+to24Hours(sheet.getCell(xi+4,i).getContents(),3);
         					ExtraChargeEnd = InDate+" "+to24Hours(sheet.getCell(xi+5,i).getContents(),4);
         					System.out.println("Dit was het");
         				}
         				
         				dateCharge.add(formatter1.parse(chargeTimeMorBegin));
         				dateCharge.add(formatter1.parse(chargeTimeMorEnd));
         				
         				dateCharge.add(formatter1.parse(chargetTimeEveBegin));
         				dateCharge.add(formatter1.parse(chargeTimeEveEnd));
         				
         				if(!Extra.isEmpty()){
         					dateCharge.add(formatter1.parse(ExtraChargeBegin));
         					dateCharge.add(formatter1.parse(ExtraChargeEnd));
         					
         				}
         				
         				
         				
         				c1.add(Calendar.DATE, 1);
         				
         				
         			}       			    			
         		}
           	
         	}
         	
         	
         	if(!pillInfo[3].contentEquals("")){io = new BufferedOutputStream(new FileOutputStream(equivitalPath.getPath()+"/"+To3DigitString(pillInfo[3])+"/Wrong_Pill.csv"));}
         	finalio = new BufferedOutputStream(new FileOutputStream(equivitalPath.getPath()+"/"+aPatientNumber+"/Core_patch_comp.csv"));
              	
         	//Second get the intake time of all the pills and the recharging times.   	
        	Sheet sheet2 = w.getSheet(1);
        	
        	
        	for(int i=8; i<sheet2.getRows() ; i++){
        	
        		String ID = sheet2.getCell(0, i).getContents();
        	       	
        		if(Integer.parseInt(aPatientNumber) == Integer.parseInt(ID) )
        		{
        			String[] ImperfectDate= sheet2.getCell(1, i).getContents().split("/");		
        			String PerfectDate = ImperfectDate[0]+"/"+ImperfectDate[1]+"/"+"20"+ImperfectDate[2];
        			c.setTime(formatter2.parse(PerfectDate));
        			c.add(Calendar.DATE, 1);  // number of days to add
        			String PerfectDate2 = formatter2.format(c.getTime());  // dt is now the new date
        			c.add(Calendar.DATE, 1);
        			String PerfectDate3 = formatter2.format(c.getTime()); 
        			
        			
        			String time1 = sheet2.getCell(2,i).getContents();
        			String time2 = sheet2.getCell(3,i).getContents();
        			String time3 = sheet2.getCell(4,i).getContents();
       		            	
//        			if( sheet.getCell(2, i).getContents().contentEquals("ng") 
//        					|| sheet.getCell(3, i).getContents().contentEquals("nvt")
//        					|| sheet.getCell(3, i).getContents().contentEquals("ng") 
//        					|| sheet.getCell(4, i).getContents().contentEquals("nvt") )
//        				{ 
//    			 
        			datePills[0] = formatter1.parse(PerfectDate+" "+time1);
        			datePills[1] = formatter1.parse(PerfectDate2+" "+time2);       				 	
       				datePills[2] = formatter1.parse(PerfectDate3+" "+time3);
       				
       				
       				
       				
        		}
         	
        	}
        	
        	
        	
         	
    	  //Finally Loop throught all the files assiocated with the patient.
           	for(int xi=0;xi<aPatientEqvuivitalFiles.size();xi++)
           	{ 		  	   
           		br = new BufferedReader(new FileReader(aPatientEqvuivitalFiles.get(xi)));
           		System.out.println("Hier gaat het om:"+aPatientEqvuivitalFiles.get(xi) );
       	
            	
           		//First row is only values.
           		String readLine = br.readLine();
           		int tempPlace = 0;
           		int pillPlace = 0;
           		    	
           		// Find Temerature place.          	        			
           		String splitedValues[] = readLine.split(",");                                                                                            
           		for(int i=0;i<splitedValues.length;i++){ if(splitedValues[i].contentEquals("Temperature")){ tempPlace=i; }  }
           		for(int i=0;i<splitedValues.length;i++){ if(splitedValues[i].contentEquals("Serial No")){ pillPlace=i; }  }
           		
           		// Loop through the single file.
           		while( (readLine = br.readLine()) !=null)
           		{
           			
           			long startTime = System.currentTimeMillis();

           			splitedValues = readLine.split(",");                                                                                            
           			dateEnd =  formatter.parse(splitedValues[0]);
                                
                                
                    if(checkTem(splitedValues,tempPlace)){
            
//           			if(first5HoursCheck == false){     		
//           				if(checkTimeDiff(dateBegin,dateEnd,18000)){
//           					System.out.println(dateEnd.toString());
//           					first5HoursCheck = true;    
//           					
//           				}      		
//           			}           			 
//           			else{             				         			
//           				if(AggraValues.isEmpty() ){
//           					if(checkTem(splitedValues)){
//               				checkWithPillSchema(splitedValues,aPillTimeSchema,aPatientNumber);              				
//               				AggraValues.add(splitedValues);
//               				dateBegin = formatter.parse(splitedValues[0]);
//           					}
//               			}
//           				else if(!checkTimeDiff(dateBegin,dateEnd,TimeLimit)){
//           					if(checkTem(splitedValues)){
//           					checkWithPillSchema(splitedValues,aPillTimeSchema,aPatientNumber);
//           					AggraValues.add(splitedValues);
//           					}
//        			
//           				}
//           				else{
//           					//System.out.println(dateBegin);
//           					//System.out.println(dateEnd);
//           					AggraValues.clear();
//           				}     		     		
//           			}
           			
 //					first5HoursCheck = false;	
                    	
                    	
                    
           			
           			if(ChargeTimeCheck(splitedValues,dateCharge,formatter1)	&& FiveHoursCheck(splitedValues,pillInfo,datePills, io , pillPlace)  ){
           				String toWrite = "";
           			
           				
           				for(int j=0;j<splitedValues.length;j++){ toWrite = toWrite+splitedValues[j]+",";} 
           				toWrite = toWrite+"\n";
           				byte bites[] = toWrite.getBytes(); 
           				finalio.write(bites);
             			
           			}
           				
           			
           			long estimatedTime = (System.currentTimeMillis() - startTime);
           			//System.out.println(estimatedTime);
                                
                                }
      	
           		}
           		
           		
       	
           		
           		
           		br.close();
           		
           	}
           	
           	if(!pillInfo[3].contentEquals("")){io.close(); ;}
           	finalio.close();
           	
       }
       catch (Exception e)
       {
           System.out.println("Er ging iets fout in Clean Equivital met deze Patient  "+aPatientNumber);
           System.out.println(pillInfo[3]);
           e.printStackTrace();
       }
    	
    	
    }
   
   public static boolean ChargeTimeCheck(String [] splitedValues, ArrayList<Date> dateCharge, DateFormat formatter1){
	 
	   Date dateValue = null;
	   boolean booret = true;
	   try {
		dateValue = formatter1.parse(splitedValues[0]);
		  
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	   
	   for(int i =0 ;i<dateCharge.size()-1;i=i+2){
		   
		  if( (!checkTimeDiff(dateCharge.get(i+1),dateValue, 900) && dateValue.after(dateCharge.get(i+1))) || (dateValue.before(dateCharge.get(i)) && !checkTimeDiff(dateValue,dateCharge.get(i), 900) )){
			  //booret = true;
			  booret = false;
			  System.out.println("----------------------------------------------------");
			  System.out.println("Eerste check was: "+checkTimeDiff(dateValue,dateCharge.get(i),900));
			  System.out.println(dateCharge.get(i).getTime() - dateValue.getTime());
			  System.out.println("Tweede check was: "+checkTimeDiff(dateCharge.get(i+1),dateValue, 900));
		      System.out.println(dateValue.getTime()- dateCharge.get(i+1).getTime() );
			  System.out.println("Dit was de date"+dateValue );
			  System.out.println("Dit was charge time begin: "+dateCharge.get(i));
			  System.out.println("Dit was charge time end: "+ dateCharge.get(i+1));
			  System.out.println("----------------------------------------------------");
			  
			 
			  
		  }
		  else{
			 
			  System.out.println("hallo");
		  }
		   
		   
	   }
	   
	   return booret;
	   
	   
	   
   }
   
   
   public static boolean checkTem(String[] splitedValues, int tempPlace)
   {
	   if(Double.parseDouble(splitedValues[tempPlace]) < 35 || Double.parseDouble(splitedValues[tempPlace]) > 41 ){
		    
		   return false;
	   }
	   else{
              
		   return true;
	   }
   }
   
   /**
    * TODO write good pill intake time.
    * 
    * @param splitedValues
    * @param aPillTimeSchema
    * @param aPatientNumber
    * @param io 
    */
   
   public static boolean FiveHoursCheck(String[] splitedValues,String[] pillInfo, Date[] pillDate,  BufferedOutputStream io, int pillPlace )
   {	   	      	
	   boolean ret = false;
	  
	  if(checkWithPillSchema(splitedValues,pillInfo, io, pillPlace)[0])
	  {
		    
		  DateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy hh:mm");        			      			
          Date dateValue = null;
		try {
			dateValue = formatter1.parse(splitedValues[0]);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}     	
       				 
       		if( (checkTimeDiff(pillDate[0],dateValue,18000) && dateValue.before(pillDate[1])) ||
        					(checkTimeDiff(pillDate[1], dateValue,18000) && dateValue.before(pillDate[2])) ||
        					checkTimeDiff(pillDate[2], dateValue,18000)){ 
       					
        		//System.out.println("Dit is hem"+dateValue );	
       			ret = true;
        	}
        		       		
       }       				       			
      
	  return ret;
	   
   }
   
   
   
   
   public static boolean[] checkWithPillSchema(String[] splitedValues,String[] pillInfo ,BufferedOutputStream io, int pillPlace ){
	          
     
       			boolean[] returns= new boolean[2];
       
       			         		
         		if(pillInfo[3].isEmpty()){returns[1] = false; }else{ returns[1] = true;}
         		
         		if(splitedValues.length < 4){
         			return returns;
         		}
         		
         		if(pillInfo[0].contentEquals(splitedValues[pillPlace]) || pillInfo[1].contentEquals(splitedValues[pillPlace]) || pillInfo[2].contentEquals(splitedValues[pillPlace]))
         		{
         			returns[0] = true;
         		}
         		else
         		{       			
         			//System.out.println("Ik ga dit schrijven "+splitedValues[0]+"  "+splitedValues[1]+" "+splitedValues[2]+"  "+splitedValues[3]+" voor Patient "+pillInfo[3]);
         			String ToWrite = "";
         			for(int j=0;j<splitedValues.length;j++){ ToWrite = ToWrite+splitedValues[j]+",";} 
         			
         			 byte bites[] = (ToWrite+"\n").getBytes(); 
         			
         			 
                     try {
						io.write(bites);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						
						
						e.printStackTrace();
					}
         			
         			returns[0] =false;
         		}       		
          	
   
         		return returns;
	   
   }
    
}


